﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Web;
using System.Net;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.IO;
using System.Linq;
using WebApplication1.MSG;

namespace WebApplication1
{
    public partial class Chief_Main : System.Web.UI.Page
    {
         string EQID = "wx000000";
        string un = "";
        string uid = "";
        string tokenValue="";
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Request["code"] == null)
            {
                string httpUrl =
                         "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8579b2dae40753d2&redirect_uri=http://www.cmuam.site/Chief_Main.aspx?response_type=code&scope=snsapi_base&state=";
                Response.Redirect(httpUrl);
            }
            else
            {
                try
                {
                    //1.微信主页判断是否存在Cookie信息，如果存在则不需要再次验证
                    //2.如果不存在，则跳转到微信OAuth统一认证页面认证，之后到此页面获取用户信息存入Cookie返回主页
                    //3.获取Code,此code只能使用一次。
                    string code = Request["code"];

                    //4.根据企业ID:XX,Secret:XXX,获取token
                    string accessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
                    string accessTokenResult = HttpGet(accessTokenUrl, "corpid=wx8579b2dae40753d2&corpsecret=JjVqfS47AEc9Z9UHhDvksIGZ_YPgW6Wjo80jGOTxKX8m8yn4VoHDaxRXJI43dIa5");
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    token mytoken = js.Deserialize<token>(accessTokenResult);
                    tokenValue = mytoken.access_token;


                    //5.获取UserInfo,包含userId
                    string userinfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";
                    string userinfojson = HttpGet(userinfoUrl, "access_token=" + tokenValue + "&code=" + code);
                    userinfo userinfo1 = js.Deserialize<userinfo>(userinfojson);
                    string UserId = userinfo1.UserId;


                    string userinfodetailURL = "https://qyapi.weixin.qq.com/cgi-bin/user/get";
                    string userinfodetailResult = HttpGet(userinfodetailURL, "access_token=" + tokenValue + "&userid=" + UserId);
                    string[] sArray = userinfodetailResult.Split(new string[] { "mobile", "gender" }, StringSplitOptions.RemoveEmptyEntries);
                    string str = sArray[1];
                    str = str.Replace("\"", "");
                    str = str.Replace(":", "");
                    str = str.Replace(",", "");
                    //Label1.Text = str;
                    Response.Cookies["UserPhone"].Value = str;
                    UserInfo us = new UserInfo();
                    us.Init(str);
                    us.Init(Request.Cookies["UserPhone"].Value.ToString());
                    //Label1.Text=us.ChineseName+",您好！";
                    if (us.ChineseName != "李传佳")
                    {
                        SendMSG sd = new SendMSG();
                        string rs = sd.Send("Leon", us.ChineseName + " 刚刚登陆！");
                    }
                }


                catch (Exception ex)
                {
                    //TODO 处理异常

                }
            }
            
        }
        public string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("http://www.cmuam.site/First_Level_Dept.aspx" 
           , false);
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Redirect("http://www.cmuam.site/Main_Task_Manage.aspx"
  , false);
        }

        protected void Button3_Click(object sender, EventArgs e)
        {

            Response.Redirect("http://www.cmuam.site/Apply_List_Chief.aspx" 
           , false);
            
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            Response.Redirect("http://www.cmuam.site/Data_Analysis.aspx" 
           , false);
            
        }
        public class userinfo
        {
            public string UserId { get; set; }
            public string DeviceId { get; set; }
        }

        public class token
        {

            public string access_token { get; set; }
            public int expires_in { get; set; }

        }
    }
}